package com.xx.sg.own.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rts.common.util.SmUtil;
import com.xx.sg.own.entity.DataSecret;
import com.xx.sg.own.entity.Dept;
import com.xx.sg.own.entity.User;
import com.xx.sg.own.service.DataSecretService;
import com.xx.sg.own.service.DataSynService;
import com.xx.sg.own.service.DeptService;
import com.xx.sg.own.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
public class DataSynServiceImpl implements DataSynService {

    @Value("${data-syn.interface-auth-secret}")
    private String INTERFACE_AUTH_SECRET;
    @Value("${data-syn.interface-auth-id}")
    private String INTERFACE_AUTH_ID;
    @Value("${data-syn.authCode}")
    private String AUTH_CODE;
    @Value("${data-syn.http-address}")
    private String HTTP_ADDRESS;

    private final String key = "1q2w3e4r5t6y7u8i";
    private final String GET_DATA_SECRET_URL = "/esb/mdm_pull/xyt-master-authorize/data-distribution-monitor";
    private final String GET_DATA_URL = "/esb/mdm_pull/xyt-master-authorize/data-pull";

    @Autowired
    private DataSecretService dataSecretService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;


    @Override
    public void dataSyn() {
        dataSyn(getSynSecret());
    }

    @Override
    public void dataSyn(String dataSecret) {
        String decryptSM4 = SmUtil.decryptSM4(dataSecret, key);
        JSONObject jsonObject = JSONObject.parseObject(decryptSM4);

        JSONArray lists = jsonObject.getJSONArray("lists");
        for (int i = lists.size() - 1; i >= 0; i--) {
            JSONObject dataSecretObject = lists.getJSONObject(i);
            synData(dataSecretObject.getString("secretType"), dataSecretObject.getString("modeCode"), dataSecretObject.getString("secret"));
        }
    }

    @Override
    public String getSynSecret() {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("interface-auth-secret", INTERFACE_AUTH_SECRET);
        headers.set("interface-auth-id", INTERFACE_AUTH_ID);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        String url = HTTP_ADDRESS + GET_DATA_SECRET_URL + "?authCode=" + AUTH_CODE;
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
        );
        DataSecret dataSecret = DataSecret.builder()
                .secret(response.getBody())
                .build();
        dataSecretService.save(dataSecret);
        return response.getBody();
    }


    private void synData(String secretType, String modeCode, String secret) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("interface-auth-secret", INTERFACE_AUTH_SECRET);
        headers.set("interface-auth-id", INTERFACE_AUTH_ID);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        String url = HTTP_ADDRESS + GET_DATA_URL + "?authCode=" + AUTH_CODE + "&secret=" + secret;
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                entity,
                String.class
        );

        String decryptSM4 = SmUtil.decryptSM4(response.getBody(), key);
        JSONObject jsonObject = JSONObject.parseObject(decryptSM4);

        JSONArray lists = jsonObject.getJSONArray("lists");
        if (modeCode.equals("test_ttyz_user_data")) {
            for (int i = 0; i < lists.size(); i++) {
                User user = JSONObject.parseObject(lists.getString(i), User.class);
                if (secretType.equals("UPDATE")) {
                    if (userService.getById(user.getId()) == null) {
                        userService.save(user);
                    } else {
                        userService.updateById(user);
                    }
                } else {
                    userService.removeById(user.getId());
                }
            }
        } else if (modeCode.equals("test_ttyz_dept_data")) {
            for (int i = 0; i < lists.size(); i++) {
                Dept dept = JSONObject.parseObject(lists.getString(i), Dept.class);
                if (secretType.equals("UPDATE")) {
                    if (deptService.getById(dept.getId()) == null) {
                        deptService.save(dept);
                    } else {
                        deptService.updateById(dept);
                    }
                } else {
                    deptService.removeById(dept.getId());
                }
            }
        }
    }
}
